package com.atguigu.spzx.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.vo.product.CategoryExcelVo;
import org.ehcache.core.util.CollectionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author：tzl
 * @Date：2024/1/30 17:43
 * @description: excel监听器
 */
public class ExcelListener<T> extends AnalysisEventListener<T> {

    /**
     * 每次批量插入数据库的数据条数，到达这个数量就清理list
     */
    private static final int BATCH_COUNT = 100;

    /**
     * 缓存数据
     */
    private List<Category> categoryBatchList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private CategoryService categoryService;

    /**
     * 通过构造器注入
     *
     * @param categoryService
     */
    public ExcelListener(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    /**
     * 解析一行就执行一次这段代码
     *
     * @param t
     * @param analysisContext
     */
    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        CategoryExcelVo categoryExcelVo = (CategoryExcelVo) t;
        Category category = new Category();
        BeanUtils.copyProperties(categoryExcelVo,category);
        categoryBatchList.add(category);

        // 达到一个批次的数量了就保存数据并且清理
        if (categoryBatchList.size() >= BATCH_COUNT) {
            categoryService.saveBatch(categoryBatchList);
            // 清理数据
            categoryBatchList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 保存剩下的数据
        if (!CollectionUtils.isEmpty(categoryBatchList)){
            categoryService.saveBatch(categoryBatchList);
            categoryBatchList.clear();
        }
    }
}
